package com.ai5suoai.ams.service;

import com.ai5suoai.ams.entity.User;
import com.ai5suoai.ams.repository.UserRepository;
import com.ai5suoai.ams.web.vo.UserVo;
import com.ai5suoai.commons.log.Logging;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * 用户的业务类
 *
 * @author chenzhenjia
 * @since 2016/3/17
 */
@Service
@Logging
public class UserService extends MongoService<User, UserVo, String> {

    @Autowired
    UserRepository userRepository;
    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    MongoRepository<User, String> getRepository() {
        return userRepository;
    }

    public User findOne(String id) {
        return userRepository.findOne(id);
    }

    /**
     * 根据用户名查询用户对象
     *
     * @param username 用户名
     * @return 返回用户的 Optional
     */
    public Optional<User> findOneByUsername(String username) {
        return Optional.ofNullable(userRepository.findOneByUsername(username));
    }

    /**
     * 根据邮箱查询用户对象
     *
     * @param email 邮箱
     * @return 返回用户的 optional 对象
     */
    public Optional<User> findOneByEmail(String email) {
        return Optional.ofNullable(userRepository.findOneByEmail(email));
    }

    /**
     * 保存用户
     *
     * @param userVo 用户对象的vo
     * @return 返回保存后的用户
     */
    public User save(UserVo userVo) {
        User user = userVo.toEntity();
        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        return userRepository.save(user);
    }

    public User acitityUser(String key) {
//        userRepository.findOneByActivationKey(key).map()
//        userRepository.save()
        return null;
    }

}
